﻿using System;

namespace octalforty.Componento.Core.Util
{
    public static class UriExtensions
    {
        /// <summary>
        /// Changes scheme of a <paramref name="uri"/> to <paramref name="scheme"/> and returns a new <see cref="Uri"/> object.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="scheme"></param>
        /// <returns></returns>
        public static Uri ChangeScheme(this Uri uri, string scheme)
        {
            return new UriBuilder(uri) { Scheme = scheme }.Uri;
        }

        /// <summary>
        /// Ensures that <paramref name="uri"/> ends with <paramref name="suffix"/>.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="suffix"></param>
        /// <returns></returns>
        public static Uri EnsureEndsWith(this Uri uri, string suffix)
        {
            var uriBuilder = new UriBuilder(uri);
            if(!uriBuilder.Path.EndsWith(suffix))
                uriBuilder.Path += suffix;

            return uriBuilder.Uri;
        }

        public static Uri AppendQueryString(this Uri uri, string key, string value)
        {
            var uriBuilder = new UriBuilder(uri);
            if(string.IsNullOrEmpty(uriBuilder.Query) || uriBuilder.Query == "?")
                uriBuilder.Query = "{0}={1}".FormatWith(key, value);
            else
                uriBuilder.Query = "{0}&{1}={2}".FormatWith(uriBuilder.Query.TrimStart('?'), key, value);

            if(!uri.AbsolutePath.EndsWith("/"))
                uriBuilder.Path = uriBuilder.Path.TrimEnd('/');

            return uriBuilder.Uri;
        }

        public static string GetLastSegment(this Uri uri)
        {
            return uri.Segments[uri.Segments.Length - 1];
        }

        public static Uri GetUriWithoutQuery(this Uri uri)
        {
            if(string.IsNullOrEmpty(uri.Query))
                return uri;

            string originalString = uri.OriginalString;

            return new Uri(originalString.Substring(0, originalString.Length - uri.Query.Length));
        }

        public static string GetBareQuery(this Uri uri)
        {
            return string.IsNullOrEmpty(uri.Query) ?
                string.Empty :
                uri.Query.Substring(1);
        }
    }
}
